//
//  HomePageVC.m
//  ImGuider
//
//  Created by 李陆涛 on 2017/12/11.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "HomePageVC.h"
#import "HomeHotCell.h"
#import "GuiderNodeCell.h"
#import "SDCycleScrollView.h"
#import "ShowAllHeadView.h"

#import "CityTourListVC.h"
#import "SpecialListVC.h"
#import "GuiderListVC.h"
#import "DIYScanViewController.h"
#import "AllSearchVC.h"
#import "GuiderDetailVC.h"
#import "ScenicDescribeVC.h"
#import "CityVC.h"
#import "WebViewVC.h"
#import "SpecialDetailVC.h"
#import "PlayerItem.h"
#import "SelectDestinationVC.h"
#import "GLHBannerView.h"
#import "LinePreDetailVC.h"

@interface HomePageVC () <UITableViewDelegate, UITableViewDataSource,AllSearchVCDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) GLHBannerView *headScrollView;

@property (nonatomic, strong) HomeModel *model;
@property (nonatomic, strong) NSArray *typeArray;

@end

@implementation HomePageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    [[PlayerItem playItemShareManager] show];
}

- (void)setupUI {
    
    self.title = @"ImGuider";
    [self barItemWithImageNameArray:@[@"扫一扫",@"搜索"] selArray:@[@"scanAction",@"searchAction"] isLeft:YES];
    self.barBGAlpha = 0;
    
    self.customBarStyle = UIStatusBarStyleLightContent;
    
    [self setAutoRowHeight:self.tableView];
    
    [self registCells:@[@"GuiderNodeCell"] tableView:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeHotCell" bundle:nil] forCellReuseIdentifier:[NSString stringWithFormat:@"HomeHotCell%d",(int)HomeCellTypeLine]];
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeHotCell" bundle:nil] forCellReuseIdentifier:[NSString stringWithFormat:@"HomeHotCell%d",(int)HomeCellTypeDestination]];
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeHotCell" bundle:nil] forCellReuseIdentifier:[NSString stringWithFormat:@"HomeHotCell%d",(int)HomeCellTypeSpecial]];
    
    
    [self closeAutomaticallyAdjustsScrollViewInsets:self.tableView];
    
    self.headScrollView = [[GLHBannerView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth * 3 / 4)];
    
    self.tableView.tableHeaderView = self.headScrollView;
    
    [ActivityIndicatorView showHUDAddedTo:self.view backgroundColor:[UIColor whiteColor]];
    [self setupData];
    
    
    [self.headScrollView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cycleDidSelectItem)]];
}

- (void)setupData {
    
    
    [NetAPIManager getHomePageWithBlock:^(HomeModel *model, NSError *error) {
        
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        self.model = model;
        [AppManager sharedManager].recommendArray =[NSMutableArray arrayWithArray:model.cities];
        [self.tableView.mj_header endRefreshing];
        
        [self setupTypeArray];
        
    }];
}

- (void)setupTypeArray {
    
    
    NSMutableArray *imageArray = [NSMutableArray array];
    
    for (SliderModel *model in self.model.sliders) {
        
        [imageArray addObject:model.picture];
    }
    [self.headScrollView setBannerImageArray:imageArray];
    
    NSMutableArray *typeArray = [NSMutableArray array];
    if (self.model.lines.count > 0) {
        [typeArray addObject:@(HomeCellTypeLine)];
    }
    if (self.model.cities.count > 0) {
        [typeArray addObject:@(HomeCellTypeDestination)];
    }
    if (self.model.albums.count > 0) {
        [typeArray addObject:@(HomeCellTypeSpecial)];
    }
    if (self.model.guiders.count > 0) {
        [typeArray addObject:@(HomeCellTypeGuider)];
    }
    
    self.typeArray = typeArray;
    
    [self.tableView reloadData];
}

- (void)scanAction {
    
    if (![IGUtil hasLoginOrPresentLogin]) {
        
        return;
    }
    
    DIYScanViewController *scanVC = [DIYScanViewController new];
    scanVC.hidesBottomBarWhenPushed = YES;
    scanVC.myDelegate = self;

    [self.navigationController pushViewController:scanVC animated:NO];
}

- (void)searchAction {
    
    AllSearchVC * vc = [[AllSearchVC alloc] init];
    
    vc.delegate = self;
    vc.hidesBottomBarWhenPushed = YES;
//    RTRootNavigationController * nav = [[RTRootNavigationController alloc] initWithRootViewController:vc];
//    [self presentViewController:nav animated:YES completion:nil];
    
    [self.navigationController pushViewController:vc animated:YES];
    
}


- (void)scanSuccess:(NSDictionary *)dict {
    
    NSString *type = dict[@"type"];
    
    if ([type isEqualToString:@"coupon"]) {
        
        [self scanCoupon:dict[@"detail"]];
        
        return;
    }
    
    [self scanOther:dict[@"message"]];
}

- (void)scanCoupon:(NSArray *)array {
    
    NSString *message = nil;
    NSString *btn = MYLocalizedString(@"PUBLIC_CONFIRM", nil);
    NSArray *couponArray = [NSArray modelArrayWithClass:[Coupon class] json:array];
    
    Coupon *coupon = couponArray.firstObject;
    
    if (!coupon || ![coupon isKindOfClass:[Coupon class]]) {
        
        coupon = nil;
    }
    
    message = [NSString localizedStringWithFormat:MYLocalizedString(@"SCAN_GET_COUPON", nil),couponArray.count];
    
    if ([coupon.infos[@"gototype"] isEqualToString:@"line"] || [coupon.infos[@"gototype"] isEqualToString:@"view"]) {
        
        btn = MYLocalizedString(@"VOUCHER_USE_NOW", nil);
        
        message = [NSString stringWithFormat:@"%@\n\n%@%@\n%@",message,coupon.infos[@"big"],coupon.infos[@"middle"],coupon.infos[@"title"]];
    }
    
    [IGAlertView alertWithTitle:MYLocalizedString(@"PUBLIC_ALERT", nil) message:message cancelButtonTitle:btn commitBtn:nil commit:nil cancel:^{
        
        // type 优惠券类型（1一元购，2免费听，3定向城市，4定向景点，5定向线路）
        if ([coupon.infos[@"gototype"] isEqualToString:@"view"]) { // 景点
            
            NSString *viewid = coupon.infos[@"gotoid"];
            
            ScenicDescribeVC *scenicVC = [ScenicDescribeVC new];
            scenicVC.scenicid = viewid;
            
            [self.navigationController pushViewController:scenicVC animated:YES];
            
        } else if ([coupon.infos[@"gototype"] isEqualToString:@"line"]) {//讲解
            
            [ActivityIndicatorView showHUDAddedTo:self.view];
            @weakify(self);
            [NetAPIManager useCouponid:coupon.couponid Block:^(NSString *lineid, NSString *errmsg) {
                
                @strongify(self);
                [ActivityIndicatorView hideHUDAddedTo:self.view];
                
                if (!errmsg) {
                    
                    LinePreDetailVC *detailVC = [IGUtil loadViewController:@"LinePreDetailVC" storyboard:@"LineDetail"];
                    detailVC.lineid = lineid;
                    
                    [self.navigationController pushViewController:detailVC animated:YES];
                    [[NSNotificationCenter defaultCenter] postNotificationName:kReloadUserDataNotif object:nil];
                } else {
                    
                    [IGUtil showToast:errmsg];
                }
                
            }];
        }
    }];
}

- (void)scanOther:(NSString *)message {
    
    if (message.length == 0) {
        message = @"兑换成功";
    }
    
    [IGAlertView alertWithTitle:MYLocalizedString(@"PUBLIC_ALERT", nil) message:message cancelButtonTitle:MYLocalizedString(@"PUBLIC_CONFIRM", nil) commitBtn:nil commit:nil cancel:nil];
}

#pragma mark   -- AllSearchVCDelegate

- (void)selectModel:(SearchResultModel *)model {
    
    if ([model.type isEqualToString:@"view"]) {
        
        ScenicDescribeVC *scenicDesVC = [ScenicDescribeVC new];
        
        scenicDesVC.hidesBottomBarWhenPushed = YES;
        
        scenicDesVC.scenicid = model.ID;
        
        [self.navigationController pushViewController:scenicDesVC animated:YES];
    }else if([model.type isEqualToString:@"city"]){
        
        CityVC * cityVC = [[CityVC alloc] init];
        
        cityVC.hidesBottomBarWhenPushed = YES;
        
        cityVC.cid = model.ID;
        
        [self.navigationController pushViewController:cityVC animated:YES];
        
    }
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.typeArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    HomeCellType type = [self.typeArray[section] integerValue];
    
    if (type == HomeCellTypeGuider) {
        return self.model.guiders.count;
    }
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HomeCellType type = [self.typeArray[indexPath.section] integerValue];
    
    if (type == HomeCellTypeGuider) {
        
        GuiderModel *model = self.model.guiders[indexPath.row];
        
        GuiderNodeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GuiderNodeCell"];
        cell.model = model;
        
        return cell;
    }
    
    NSString *idf = [NSString stringWithFormat:@"HomeHotCell%d",(int)type];
    
    HomeHotCell *cell = [tableView dequeueReusableCellWithIdentifier:idf];
    
    cell.type = type;
    cell.superVC = self;
    
    switch (type) {
        case HomeCellTypeLine:
            cell.dataSource = self.model.lines;
            break;
        case HomeCellTypeDestination:
            cell.dataSource = self.model.cities;
            break;
        case HomeCellTypeSpecial:
            cell.dataSource = self.model.albums;
            break;
            
        default:
            break;
    }
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HomeCellType type = [self.typeArray[indexPath.section] integerValue];
    
    if (type != HomeCellTypeGuider) {
        return;
    }
    GuiderModel *model = self.model.guiders[indexPath.row];
    
    GuiderDetailVC *detailvc = [GuiderDetailVC new];
    detailvc.guiderID = model.guideid;
    detailvc.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:detailvc animated:YES];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    HomeCellType type = [self.typeArray[section] integerValue];
    ShowAllHeadView *headview = [ShowAllHeadView getHeadViewWithTableView:tableView];
    headview.delegate = self;
    headview.type = type;
    
    return headview;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    HomeCellType type = [self.typeArray[section] integerValue];
    
    if (type == HomeCellTypeTiket) {
        return 8;
    }
    
    return 0.01;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat offeset = scrollView.contentOffset.y;
    CGFloat height = kScreenWidth * 3 / 4;
    
    self.barBGAlpha = offeset / height;
    
    if (self.barBGAlpha > 0.8) {
        self.customBarStyle = UIStatusBarStyleDefault;
    } else {
        self.customBarStyle = UIStatusBarStyleLightContent;
    }
    
    if (offeset <= 0) {
        
        [self.headScrollView setOffSetY:offeset];
    } else {
        
        [self.headScrollView setOffSetY:0];
    }
    
}

#pragma mark- headview delegate
- (void)showAllAction:(ShowAllHeadView *)tableHeadView {
    
    HomeCellType type = tableHeadView.type;
    
    switch (type) {
        case HomeCellTypeLine: {
            
            CityTourListVC *vc = [CityTourListVC new];
            vc.isPopular = YES;
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case HomeCellTypeDestination: {
            
            SelectDestinationVC *destination = [SelectDestinationVC new];
            destination.hidesBottomBarWhenPushed = YES;
            destination.isHiddenBootomBar = YES;
            [self.navigationController pushViewController:destination animated:YES];
        }
            break;
        case HomeCellTypeSpecial: {
            
            SpecialListVC *vc = [SpecialListVC new];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case HomeCellTypeGuider: {
            
            GuiderListVC *guiderVC = [GuiderListVC new];
            guiderVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:guiderVC animated:YES];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - SDCycleScrollViewDelegate
/** 点击图片回调 */
- (void)cycleDidSelectItem {
    
    NSInteger index = self.headScrollView.index;
    
    if (self.model.sliders.count <= index) {
        
        return;
    }
    
    //0:nolink, 1:weblink, 2:city, 3:view, 4:line, 5:album
    SliderModel *model = self.model.sliders[index];
    
    switch (model.linktype.integerValue) {
        case 0: {//nolink
            
        }
            break;
        case 1: {//weblink
            WebViewVC *webVC = [WebViewVC new];
            webVC.url = model.linkto;
            webVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:webVC animated:YES];
        }
            break;
        case 2: {//city
            
            CityVC * cityVC = [[CityVC alloc] init];
            
            cityVC.hidesBottomBarWhenPushed = YES;
            
            cityVC.cid = model.linkto;
            
            [self.navigationController pushViewController:cityVC animated:YES];
        }
            break;
        case 3: {//view
            
            ScenicDescribeVC *scenicDesVC = [ScenicDescribeVC new];
            
            scenicDesVC.hidesBottomBarWhenPushed = YES;
            
            scenicDesVC.scenicid = model.linkto;
            [self.navigationController pushViewController:scenicDesVC animated:YES];
        }
            break;
        case 4: {//line
            
            City *city = [City new];
            city.cid = @(model.linkto.integerValue);
            
            CityTourListVC *vc = [CityTourListVC new];
            vc.city = city;
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 5: {//album
            
            SpecialDetailVC * specialDetailVC = [[SpecialDetailVC alloc] init];
            
            specialDetailVC.hidesBottomBarWhenPushed = YES;
            [self.superVC.navigationController pushViewController:specialDetailVC animated:YES];
        }
            break;
            
        default:
            break;
    }
}

@end



